<?php


namespace app\api\service;

use app\common\model\Config;
use Endroid\QrCode\QrCode;
use think\App;
use think\Env;
use think\Exception;
use Yansongda\Pay\Pay;

/**
 * 根据关键字搜索文章链接
 * 文档地址:https://www.juhe.cn/docs/api/id/743
 * 聚合数据-财经新闻
 * Class FetchArticleService
 * @package app\api\service
 */
class CaiJingService
{

    private $key;

    public function __construct()
    {
        $this->key = Config::where('name','api_key')
            ->where('group','grapevine_config')
            ->value('value');
    }

    /**
     * 获取文章列表
     * @param string $word 关键字
     * @param int $page 页码
     * @param int $limit 每页多少条
     */
    public function getList(string $word, int $page = 1, int $limit = 100)
    {
        $url = 'http://apis.juhe.cn/fapigx/caijing/query';
        try {
            $postData = [
                'key' => $this->key,//在个人中心->我的数据,接口名称上方查看
                'word' => $word,//检索关键词
                'num' => $limit,//返回数量
                'page' => $page,//翻页
                //'rand'=>1,//是否随机获取
            ];

            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => http_build_query($postData),
                CURLOPT_HTTPHEADER => [
                    "Content-Type: application/x-www-form-urlencoded"
                ],
            ]);

            $response = curl_exec($curl);
            curl_close($curl);

            $resData = json_decode($response, true);
            if (!$resData['error_code']){
                //抓取数据成功
                $res = [
                    'code' => 1,
                    'msg'=>$resData['reason'],
                    'data' => $resData['result']
                ];
            }else{
                $res = [
                    'code' => 0,
                    'msg'=>$resData['reason'],
                    'data' => []
                ];
            }
        } catch (Exception $exception) {
            $res = [
                'code' => 0,
                'msg'=>'系统错误:' . $exception->getMessage() . $exception->getLine(),
                'data' => []
            ];
        }
        return $res;
    }
}